/*
 *  $Id: Loading.cs 1198 2010-11-20 14:32:09Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008-2009 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System.Threading;

using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;

namespace Ragima {
    /// <summary>
    /// Поддержка экрана загрузки данных.
    /// TODO : переделать на сцену.
    /// </summary>
    public static class Loading {
        private const int loadingX = Constants.DisplayWidth/2;
        private const int loadingY = Constants.DisplayHeight/2 - 120;
        private const int progressX = (Constants.DisplayWidth - progressWidth) / 2;
        private const int progressY = Constants.DisplayHeight/2;
        private const int progressWidth = 800;
        private const int progressHeight = 10;
        private const int levelSteps = 8;
        private static int progressMax;
        private static int progressValue;
        private static LoadingItem[] items;

        public static void Draw() {
            Display.BeginFrame();
            Display.Clear();
            Data.LoadingText.Draw(loadingX, loadingY);
            for (int i = 0; i < progressValue; i++) {
                Data.LoadingBall.Color = Color.FromArgb(items[i].Size * items[i].Level / levelSteps, Color.White); 
                Data.LoadingBall.Draw(items[i].X, items[i].Y);
            }
            Display.EndFrame();
            Core.KeepAlive();
        }

        public static void ProgressReset(int max) {
            progressMax = max;
            progressValue = 0;
            items = new LoadingItem[max];
            for (int i = 0; i < max; i++) {
                LoadingItem item;
                item.X = progressX + progressWidth * i / max;
                item.Y = progressY + Randomizer.Global.Next(progressHeight) - progressHeight/2;
                item.Size = Randomizer.Global.Next(80, 256);
                item.Level = 0;
                items[i] = item;
            }
            Draw();
        }

        public static void ProgressInc() {
            ProgressInc(1);
        }

        public static void ProgressInc(int value) {
            progressValue += value;
            if (progressValue > progressMax) progressValue = progressMax;
            Update();
        }

        public static void Wait() {
            for (int i = 0; i < levelSteps*2; i++) {
                Update();
                Thread.Sleep(Constants.FrameTime);
            }
        }

        private static void Update() {
            for (int i = 0; i < progressValue; i++) {
                if (items[i].Level < levelSteps) items[i].Level++;
            }
            Draw();
        }

        private struct LoadingItem {
            public int X, Y, Size, Level;
        }
    }
}
